package com.such.kit;

/**
 * @author SUCH
 * <pre>
 * 获取线程异步返回值
 * </pre>
 */
public class SyncValue<Input, Return> implements Runnable {

	private Callable<Input, Return> callable;
	private Input param;
	private Return value;
	private boolean runOver = false;
	private boolean runSuccess = true;
	private Exception e;

	public SyncValue(Callable<Input, Return> callable, Input param) {
		this.callable = callable;
		this.param = param;
	}

	public void run() {
		try {
			this.value = this.callable.call(this.param);
		} catch (Exception e) {
			this.runSuccess = false;
			this.e = e;
			Logger.error(getClass(), "线程回调异常", e);
		}
		this.runOver = true;
	}

	/**
	 * <pre>
	 * 获取线程执行的返回值，此方法将导致线程阻塞
	 * </pre>
	 * @return 异步返回值
	 * @throws Exception
	 */
	public Return getValue() throws Exception {
		while (!this.runOver) {
			Thread.sleep(1000);
		}
		if (!this.runSuccess) {
			throw this.e;
		}
		return this.value;
	}

}
